from flask import jsonify
from sqlalchemy import func

from supermarket.app import app, db
from supermarket.app.models import Employee, Product, PurchaseMaster, PurchaseDetail


# 统计查询模块

# 查询所有员工信息
@app.route('/stats/employees', methods=['GET'])
def get_stats_employees():
    employees = Employee.query.all()
    total_employees = len(employees)
    return jsonify({
        '员工': [employee.to_dict() for employee in employees],
        '员工总数': total_employees
    })


# 查询所有商品信息并统计
@app.route('/stats/products', methods=['GET'])
def get_stats_products():
    products = Product.query.all()
    total_products = len(products)
    average_price = db.session.query(func.avg(Product.price)).scalar()
    max_price = db.session.query(func.max(Product.price)).scalar()
    min_price = db.session.query(func.min(Product.price)).scalar()
    return jsonify({
        '商品': [product.to_dict() for product in products],
        '商品总数': total_products,
        '平均价': average_price,
        '最高价': max_price,
        '最低价': min_price
    })


# 查询所有采购信息并统计
@app.route('/stats/purchases', methods=['GET'])
def get_stats_purchases():
    purchases = PurchaseMaster.query.all()
    total_purchases = len(purchases)
    total_amount = db.session.query(func.sum(PurchaseDetail.unit_price * PurchaseDetail.quantity)).scalar()
    return jsonify({
        '购买清单': [purchase.to_dict() for purchase in purchases],
        '总单数': total_purchases,
        '总开销': total_amount
    })